package com.ds.robot.assistant.service.yunxiao;

import com.aliyun.sdk.service.devops20210625.models.ListProjectsRequest;
import com.aliyun.sdk.service.devops20210625.models.ListProjectsResponse;
import com.aliyun.sdk.service.devops20210625.models.ListProjectsResponseBody;
import com.google.common.collect.Lists;
import com.ds.robot.assistant.entity.ProjectInfoEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.PreDestroy;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 * 作用：
 *
 * @author WeiShaoying
 * 
 */
@Component
@Slf4j
@SuppressWarnings("SpellCheckingInspection")
public class YunXiaoProjectClient extends YunXiaoBase {

    private final List<String> ignoreList = Lists.newArrayList("草稿", "文档", "公共空间");

    @PreDestroy
    private void destroy() {
        log.info("云效 Project Client准备关闭");
        asyncClient.close();
        log.info("云效 Project Client关闭成功");
    }

    public List<ProjectInfoEntity> queryProjectList() {
        List<ProjectInfoEntity> list = Lists.newArrayList();
        long start = System.currentTimeMillis();

        // Parameter settings for API request
        ListProjectsRequest listProjectsRequest = ListProjectsRequest.builder()
                .maxResults(200L)
                .organizationId(ORGANIZATION_ID)
                .category("Project")
                // Request-level configuration rewrite, can set Http request parameters, etc.
                // .requestConfiguration(RequestConfiguration.create().setHttpHeaders(new HttpHeaders()))
                .build();

        // Asynchronously get the return value of the API request
        CompletableFuture<ListProjectsResponse> response = asyncClient.listProjects(listProjectsRequest);
        // Synchronously get the return value of the API request
        ListProjectsResponse resp = response.join();

        if (resp != null && resp.getStatusCode().equals(200)) {
            ListProjectsResponseBody body = resp.getBody();
            if (Objects.isNull(body)) {
                return Collections.emptyList();
            }
            List<ListProjectsResponseBody.Projects> projectList = body.getProjects();
            if (CollectionUtils.isEmpty(projectList)) {
                log.warn("查询项目为空");
                return Collections.emptyList();
            }
            log.info("查询项目总数量={}", body.getTotalCount());

            list = projectList.stream().filter(project -> !this.isIgnoreProject(project.getName())).map(projects -> {
                ProjectInfoEntity entity = new ProjectInfoEntity();
                entity.setSpaceId(projects.getIdentifier());
                entity.setName(projects.getName());
                entity.setScope(projects.getScope());
                entity.setDescription(projects.getDescription());
                return entity;
            }).collect(Collectors.toList());
        }

        // 关闭后再次调用会报错
        // asyncClient.close();

        long end = System.currentTimeMillis();
        log.info("查询云效项目耗时：{}毫秒 ", (end - start));
        return list;
    }

    private boolean isIgnoreProject(String name) {
        return ignoreList.stream().anyMatch(name::contains);
    }
}
